/**
 * @description  组合跟踪
 * @author shenhong
 */
import React, { PropTypes, PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Divider, Input, message, Row, Col, TreeSelect, Table } from 'antd';
import { FirstHeaderC, DATA_ENTRY, TableC, NoQueryC, PrimaryC, PrimaryGhostC, AdvancedSearch } from '../../../comps';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import myStyle from './index.less';
import uuid from 'es6-uuid';
import colorArr from '../../../css/colors.js';
import { fixedNum } from '../../../utils/utils';
import { isZiGuanEvir } from '../../../utils/commonFunc';
const FormItem = Form.Item;

@Form.create()
class PortfolioTracking extends PureComponent {
  constructor() {
    super();
    this.data = [];
    this.data1 = [];
    this.compareDatas = [];
    this.state = {
      useKeys: [], // 树形选择框里选择的值
      expandRow: [], // 展开的行id
      dataSource: [], // 表格数据
      isChange: false, // 选择框里的值是否改变
      columns: [], // 表格列
      seeRowId: [], // 可是行id
      selectId: [], // 树形框选择后的id（包括父级）
      length1: 0, // 表格展开行1   不包括展开的children
      length2: 0, // 表格展开行2  （展开的children）
    };
  }
  componentDidMount() {
    this.timer && clearInterval(this.timer);
    this.timer = null;
    const { dispatch } = this.props;
    if (isZiGuanEvir()) {
      dispatch({
        type: 'portfolioTrackingM/getColumn',
        payload: {},
        callback: (res) => {
          this.setState({
            columns: res.columns,
          });
        },
      });
    } else {
      dispatch({
        type: 'portfolioTrackingM/getProductData',
        payload: {},
        callback: (res) => {
          const columns = res.columns;
          const useDataSource = this.addId(res.dataSource);
          this.setState({
            columns: columns,
            useDataSource: useDataSource,
          });
        },
      });
    }
  }

  // 离开页面时销毁定时器
  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
    this.timer = null;
  }

  // 找出根节点下子节点的id
  setVisiable = (record, openRow) => {
    const arr = record;
    if (arr && arr.length) {
      arr.map((item) => {
        if (item.children) {
          openRow.map((items) => {
            if (item.sortId == items) {
              this.data.push(item.sortId);
            }
          });
        }
        item.product ? null : this.setVisiable(item.children, openRow);
      });
    }
    return this.data;
  };

  // 去除数组重复部分
  setVisiable2 = (arr1, arr2) => {
    let data = arr1.filter((item) => !arr2.some((e) => e === item));
    return data;
  };

  setVisiable3 = (arr1, arr2) => {
    let data = arr1.filter((item) => !arr2.some((e) => e.id === item.id));
    return data;
  };

  // 取出展开行的下层子节点id
  getId = (id, arr) => {
    let data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        if (item.children) {
          data.push({ id: item.portfolioCode, isChildren: item.product, pid: id, sortId: item.sortId, groupId: item.groupId });
        }
      });
    }
    return data;
  };

  // 获取该行下所有子元素id
  getId2 = (id, arr) => {
    if (arr && arr.length) {
      arr.map((item) => {
        this.data1.push({ id: item.portfolioCode, pid: id, isChildren: item.product, sortId: item.sortId, groupId: item.groupId });
        !item.product ? this.getId2(item.portfolioCode, item.children) : null;
      });
    }
    return this.data1;
  };

  //减去关闭行叶子节点的children
  setLength = (record, expandRow) => {
    let length = 0;
    const arr = record instanceof Array ? record : [record];
    arr.map((item) => {
      expandRow.map((items) => {
        if (item.product) {
          if (item.sortId == items) {
            length = item.children && item.children.length ? this.state.length2 - item.children.length : this.state.length2;
          }
        } else {
          this.setLength(item.children, this.state.expandRow);
        }
      });
    });
    this.setState({
      length2: length,
    });
  };

  // 展开闭合行操作
  onExpandChange = (expanded, record) => {
    const { seeRowId, dataSource, length1, length2 } = this.state;
    let rowdata = JSON.parse(JSON.stringify(this.state.expandRow));
    if (expanded) {
      const length = length1 + length2 + 1;
      if (length >= 100) {
        message.warning('超过最大展开行，请关闭一些展开行');
      } else {
        rowdata.push(record.sortId.toString(16));
        const iaArr = this.getId(record.portfolioCode, record.children); // 展开行下层子元素id
        const seeRow = seeRowId.concat(iaArr);
        this.setState(
          {
            expandRow: rowdata, // 当前展开行
            seeRowId: seeRow, // 当前可视行id数组
            length1: seeRow.length, // 当前表格行数
          },
          () => {
            this.goToInfo();
          },
        );
      }
    } else {
      const length = length1 + length2;
      const openRow = rowdata.filter((item) => item !== record.sortId);
      this.data = []; // 清空公共变量
      const visiable = this.setVisiable(record.children, openRow); // 找到根节点下子元素的id
      const datas = this.setVisiable2(openRow, visiable); // 去除重复部分
      this.data1 = []; // 清空公共变量
      const iaArr = this.getId2(record.id, record.children); // 闭合行的所有元素id
      const showId = this.setVisiable3(seeRowId, iaArr); //整理发给后台的数据
      this.setLength(record, this.state.expandRow); //减去关闭行内children的长度
      this.setState(
        {
          expandRow: datas, // 当前展开行
          seeRowId: showId, // 当前可视行id数组
          length1: showId.length, // 当前表格行数
        },
        () => {
          this.goToInfo();
        },
      );
    }
  };

  // 表格添加唯一标识
  addId = (datas) => {
    let arr = [];
    datas.forEach((item) => {
      (item.sortId = uuid(32)), // 生成唯一的标识
        arr.push(item);
      if (item.children && item.children.length > 0) {
        this.addId(item.children);
      }
    });
    return arr;
  };

  //接口返回数据children添加唯一标识id
  addChildId = (arr) => {
    let data = arr;
    if (data && data.length) {
      data.map((item) => {
        item.sortId = uuid(32);
      });
    }
    return data;
  };

  // 拼接表格数据
  addTableData = (arr1, arr2) => {
    let newDataSource = arr1;
    let length = 0;
    if (arr1 && arr1.length && arr2 && arr2.length) {
      newDataSource.map((item) => {
        arr2.map((items) => {
          if (item.sortId == items.sortId) {
            item.totalValue = items.totalValue;
            item.weight = items.weight;
            item.totalPnl = items.totalPnl;
            if (items.children !== null) {
              item.product ? (item.children = this.addChildId(items.children)) : null;
              length = this.state.length2 + items.children.length;
            }
          } else if (!item.product) {
            this.addTableData(item.children, arr2);
          }
        });
      });
    }
    this.setState({
      //   dataSource:newDataSource,
      length2: length,
    });
    // return newDataSource;
  };

  // 总盈亏正红负绿表示
  redAndGreen = (text) => {
    const textColor = colorArr.debtAndProfit.text;
    let color = textColor[3];
    if (text > 0) {
      color = `${textColor[0]}`;
    } else if (text < 0) {
      color = `${textColor[1]}`;
    }
    const tet = text !== undefined && text !== null ? text.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') : text;
    return <span style={{ color: `${color}` }}>{tet}</span>;
  };

  // 改变columns属性
  changeColumns = (columns) => {
    let arr = columns;
    arr.map((item) => {
      if (item.key == 'costPrice' || item.key == 'newPrice' || item.key == 'totalValue' || item.key == 'weight') {
        item.align = 'right';
        item.render = (text) => {
          return text !== null && text !== undefined ? fixedNum(text, 2) : '';
        };
      } else if (item.key == 'totalPnl') {
        item.render = (text) => {
          return this.redAndGreen(text);
        };
      }
      if (item.key == 'portfolioName' || item.key == 'assetType' || item.key == 'stockCode' || item.key == 'stockName') {
        item.render = (text) => {
          return text ? text : '';
        };
      }
    });
    return arr;
  };

  // 渲染表格
  tableRender = () => {
    const { columns, dataSource } = this.state;
    //  const {loading} = this.props;
    const newColumns = this.changeColumns(columns);
    return (
      <div style={{ marginTop: '10px' }}>
        <TableC
          columns={newColumns}
          dataSource={dataSource}
          // loading={loading}
          rowKey='sortId'
          hidePage={true}
          expandedRowKeys={this.state.expandRow} // 展开的行
          onExpand={(expanded, record) => this.onExpandChange(expanded, record)} // 点击行展开事件
        />
      </div>
    );
  };

  // 获取表格数据中product为true的id
  compareData = (e) => {
    e.map((item) => {
      if (item.product) {
        this.compareDatas.push(item.sortId);
      }
      item.children && item.children.length ? this.compareData(item.children) : null;
    });
    return this.compareDatas;
  };

  // 整理发给接口的数据
  changeUseData = (seeRowId, expandRow, compareId) => {
    const data = seeRowId;
    data.map((item1) => {
      item1.isChildren = false;
      expandRow.map((item2) => {
        compareId.map((item3) => {
          if (item1.sortId == item2) {
            if (item1.sortId == item3) {
              item1.isChildren = true;
            }
          }
        });
      });
    });
    return data;
  };

  // 刷新按钮事件
  goToInfo = () => {
    this.compareDatas = [];
    const { seeRowId, expandRow, dataSource, useKeys } = this.state;
    const { dispatch } = this.props;
    let useData;
    const compareId = this.compareData(dataSource); // 获取表格数据中叶子节点的id
    useData = this.changeUseData(seeRowId, expandRow, compareId);
    if (useKeys.length) {
      dispatch({
        type: 'portfolioTrackingM/getRowInfo',
        payload: useData,
        callback: (res) => {
          this.addTableData(this.state.dataSource, res);
        },
      });
      if (this.timer) clearInterval(this.timer);
      this.timer = null;
      this.timer = setInterval(() => {
        dispatch({
          type: 'portfolioTrackingM/getRowInfo',
          payload: useData,
          callback: (res) => {
            this.addTableData(this.state.dataSource, res);
          },
        });
      }, 10000);
    } else {
      if (this.timer) clearInterval(this.timer);
      this.timer = null;
    }
  };

  // 组合名称选完后过滤未选择的数据
  getChildren = (arr1, arr2) => {
    let datas = [];
    arr1.map((item) => {
      arr2.map((items) => {
        if (item == items.sortId) {
          datas.push(items);
        }
      });
    });
    return datas;
  };

  // 下拉菜单闭合或打开时回调
  changeStatus = (open, value) => {
    const { useKeys, useDataSource, selectId } = this.state;
    const datas = value;
    if (!open) {
      if (datas !== undefined) {
        if (datas.sort().toString() !== useKeys.sort().toString()) {
          this.setState({ expandRow: [] });
          let arrs = [];
          useDataSource.map((item) => {
            selectId.map((item1) => {
              if (item.sortId == item1) {
                arrs.push({
                  portfolioName: item.portfolioName,
                  id: item.id,
                  groupId: item.id,
                  sortId: item.sortId,
                  portfolioCode: item.portfolioCode,
                  product: item.product || false,
                  children: item.children && item.children.length ? this.getChildren(selectId, item.children) : null,
                });
              }
            });
          });
          this.setState(
            {
              useKeys: datas,
              dataSource: arrs,
            },
            () => {
              const { dataSource } = this.state;
              let data = [];
              dataSource.map((item) => {
                data.push({ id: item.portfolioCode, isChildren: item.product, pid: '', sortId: item.sortId, groupId: item.groupId });
              });
              this.setState(
                {
                  seeRowId: data,
                },
                () => {
                  this.goToInfo();
                },
              );
            },
          );
        }
      } else {
        this.setState({ useKeys: [] });
      }
    }
  };

  changeStatusZG = (open, value) => {
    const { useKeys, selectId } = this.state;
    const datas = value;
    let useDataSource = this.props.productAGroupM.products;
    console.log(datas);
    if (!open) {
      if (datas && datas.length > 0) {
        if (datas.sort().toString() !== useKeys.sort().toString()) {
          this.setState({ expandRow: [] });
          let arrs = [];
          useDataSource.map((item) => {
            datas.map((item1) => {
              if (item.value == item1) {
                arrs.push({
                  portfolioName: item.portfolioName,
                  id: item.id,
                  sortId: uuid(32),
                  product: true,
                  portfolioCode: item.portfolioCode,
                  children: [],
                });
              }
            });
          });
          this.setState(
            {
              useKeys: datas,
              dataSource: arrs,
            },
            () => {
              const { dataSource } = this.state;
              let data = [];
              dataSource.map((item) => {
                data.push({ id: item.portfolioCode, isChildren: item.product, sortId: item.sortId });
              });
              this.setState(
                {
                  seeRowId: data,
                },
                () => {
                  this.goToInfo();
                },
              );
            },
          );
        }
      } else {
        this.setState({
          useKeys: [],
          dataSource: [],
        });
      }
    }
  };

  // 将树形选择框数据更改为两层树形结构
  changeTree = (arr) => {
    let datas = [];
    if (arr && arr.length) {
      arr.map((item) => {
        datas.push({
          title: item.portfolioName,
          value: item.sortId,
          key: item.sortId,
          children: item.children && item.children.length ? this.changeTree2(item.children) : null,
        });
      });
    }
    return datas;
  };

  // 更改树形数据
  changeTree2 = (arr) => {
    let data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        data.push({
          title: item.portfolioName,
          value: item.sortId,
          key: item.sortId,
        });
      });
    }
    return data;
  };

  // 选择值的事件
  showwwww = (value, node, extra) => {
    this.compareDatas = [];
    let datas = [];
    const checkedNodes = extra.checkedNodes;
    const halfCheckedKeys = extra.halfCheckedKeys;
    checkedNodes.map((item) => {
      datas.push(item.key);
    });
    const data = datas.concat(halfCheckedKeys);
    this.setState({ selectId: data });
  };

  // 取消选择事件
  showwwww2 = (value, node, extra) => {
    this.compareDatas = [];
    let datas = [];
    const checkedNodes = extra.checkedNodes;
    const halfCheckedKeys = extra.halfCheckedKeys;
    checkedNodes.map((item) => {
      datas.push(item.key);
    });
    const data = datas.concat(halfCheckedKeys);
    this.setState({ selectId: data });
  };

  render() {
    const { useDataSource, useKeys } = this.state;
    const treeDatas = this.changeTree(useDataSource);

    let dataSource = isZiGuanEvir()
      ? [
          {
            dataIndex: 'portfolioCode',
            title: '产品名称',
            type: DATA_ENTRY.PRODUCTLIST,
            multiple: true,
            allowClear: true,
            maxTagCount: 0,
            onDropdownVisibleChange: (open, value) => this.changeStatusZG(open, value),
          },
        ]
      : [
          {
            dataIndex: 'name',
            title: '组合名称',
            type: DATA_ENTRY.TREESELECT,
            dataSource: treeDatas,
            isMultiple: true,
            treeCheckable: true,
            allowClear: true,
            maxTagCount: 0,
            onSelect: (value, node, extra) => this.showwwww(value, node, extra), // 选中值后将父级id及本身id放入state管理
            onDeselect: (value, node, extra) => this.showwwww2(value, node, extra), // 取消选中后将父级id及本身id放入state管理
            onDropdownVisibleChange: (open, value) => this.changeStatus(open, value), // 下拉框关闭时触发
          },
        ];
    return (
      <div>
        <div className={myStyle.bodyArea}>
          <div className='mainArea'>
            <FirstHeaderC title='组合跟踪' />
            <AdvancedSearch
              dataSource={dataSource}
              allowClear={false}
              allowQuery={false}
              selfButt={
                <PrimaryGhostC
                  title='刷新'
                  onClick={() => {
                    this.goToInfo();
                  }}
                />
              }
            />
            {useKeys && useKeys.length ? (
              this.tableRender()
            ) : (
              <div style={{ marginTop: '10px' }}>
                <NoQueryC />
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }
}
export default connect(({ portfolioTrackingM, productAGroupM }) => ({
  portfolioTrackingM,
  productAGroupM,
}))(PortfolioTracking);
